package cn.smbms.controller;

import cn.smbms.pojo.PageSupport;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import org.apache.log4j.Logger;
import org.aspectj.bridge.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    private Logger logger = Logger.getLogger(UserController.class);
    private ArrayList<User> userList = new ArrayList<User>();
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    @RequestMapping(value = "/userlist.html")
    public String getUserList(Model model,
                              @RequestParam(value = "queryname",required = false) String queryUserName,
                              @RequestParam(value = "queryUserRole",required = false) String queryUserRole,
                              @RequestParam(value = "pageIndex",required = false) String pageIndex){
        logger.info("getUserList -----> queryUserName:"+queryUserName);
        logger.info("getUserList -----> queryUserRole:"+queryUserRole);
        logger.info("getUserList -----> pageIndex:"+pageIndex);
        int _queryUserRole = 0;
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        if (queryUserName == null){
            queryUserName = "";
        }
        if (queryUserRole != null && !queryUserRole.equals("")){
            _queryUserRole = Integer.parseInt(queryUserRole);
        }
        if (pageIndex != null){
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            }catch (Exception e){
                return "redirect:/user/syserror.html";
            }
        }
        //总数量（表）
        int totalCount = userService.getUserCount(queryUserName,_queryUserRole);
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        //控制首页和尾页
        if (currentPageNo<1){
            currentPageNo = 1;
        }else if (currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;
        }
        userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo,pageSize);
        model.addAttribute("userList",userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        model.addAttribute("roleList",roleList);
        model.addAttribute("queryUserName",queryUserName);
        model.addAttribute("queryUserRole",queryUserRole);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("currentPageNo",currentPageNo);
        return "userlist";
    }

    //示例25
    @RequestMapping(value = "/syserror.html")
    public String syserror(){return "syserror";}

    public UserController(){
        try {//初始化用户数据
            userList.add(new User(2,"liming","李明","0000000",2,
                    new SimpleDateFormat("yyyy-MM-dd").parse("1983-12-10"),
                    "13688884457","北京市东城区前门东大街9号",2,new Date(),
                    1,new Date()));
            userList.add(new User(5,"hanlubiao","韩路彪","0000000",2,
                    new SimpleDateFormat("yyyy-MM-dd").parse("1984-06-05"),
                    "18567542321","北京市朝阳区北辰中心12号",2,new Date(),
                    1,new Date()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //没有查询条件的情况下，获取userList（公共查询）
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(Model model){
        logger.info("无查询条件下，获取userList（公共查询） ====== userList");
        model.addAttribute("queryUserList",userList);
        return "user/userlist";
    }

    private ArrayList<User> queryUserList = new ArrayList<User>();
    public String list(@RequestParam(value = "userName",required = false)String userName,Model model){
        logger.info("查询条件：userName："+userName + ",获取userList=====");
        if (userName != null && !userName.equals("")){
            for (User user:userList){
                if (user.getUserName().indexOf(userName) != -1){
                    queryUserList.add(user);
                }
            }
            model.addAttribute("queryUserList",queryUserList);
        }else {
            model.addAttribute("queryUserList",userList);
        }
        return "user/userlist";
    }

    //示例17login()方法实现跳转到系统登录页
    @RequestMapping(value = "/login.html")
    public String login(){
        logger.debug("UserController welcome SMBMS============================");
        return "login";
    }


    //示例18  实现登录
    @RequestMapping(value = "/dologin.html",method = RequestMethod.POST)
    public String doLogin(@RequestParam String userCode, @RequestParam String userPassword, HttpSession session, HttpServletRequest request){
        logger.debug("doLogin=======================================================");
        //调用service方法，进行用户匹配
        User user = userService.login(userCode,userPassword);
        if (null != user){//登录成功
            //放入session
            session.setAttribute(Constants.USER_SESSION,user);
            //页面跳转（frame.jsp）
            return "redirect:/user/main.html";
        }else {
            //页面跳转（login.jsp）
            request.setAttribute("error","用户名或密码不正确");
            return "login";
        }
    }
    @RequestMapping(value = "/main.html")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/user/login.html";
        }
        return "frame";
    }

    //示例22
    @RequestMapping(value = "exlogin.html",method = RequestMethod.GET)
    public String exLogin(@RequestParam String userCode,@RequestParam String userPassword){
        logger.debug("exLogin===================================");
        //调用service方法，进行用户匹配
        User user = userService.login(userCode,userPassword);
        if (null != user){//登录失败
            throw new RuntimeException("用户名或密码不正确");
        }
        return "redirect:/user/main.html";
    }
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest req){
        req.setAttribute("e",e);
        return "error";
    }

    //第11章示例1
    //addUser方法，从列表页进入新增页
    @RequestMapping(value = "/useradd.html",method = RequestMethod.GET)
    public String addUser(@ModelAttribute("user")User user){return "useradd";}

    //第11章示例2
   /* @RequestMapping(value = "/addsave.html",method = RequestMethod.POST)
    public  String addUserSave(User user,HttpSession session){
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
    user.setCreationDate(new Date());
    if (userService.add(user)){
        return "redirect:/user/userlist.html";
    }
    return "useradd";
    }*/
    //第11章示例20
    @RequestMapping(value = "/useraddsave.html",method = RequestMethod.POST)
    public  String addUserSave(User user, HttpSession session, HttpServletRequest request, @RequestParam(value = "a_idPicPath",
            required = false)MultipartFile[] attachs){
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
        logger.info("uploadFile path===============>"+path);
        for (int i =0;i<attachs.length;i++ ){
            MultipartFile attach = attachs[i];
        }
        //判断文件是否为空
        if (!attach.isEmpty()){
            String oldFileName = attach.getOriginalFilename();//原文件名
            logger.info("uploadFile oldFileName===============>"+oldFileName);
            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            logger.debug("uploadFile prefix===============>"+prefix);
            int filesize = 500000;
            logger.debug("uploadFile size=================>"+attach.getSize());
            if (attach.getSize()>filesize){
                request.setAttribute("uploadFileError"," * 上传文件大小不得超过 500KB");
                return "useradd";
            }else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){
                String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
                logger.debug("new fileName============="+attach.getName());
                File targetFile = new File(path,fileName);
                if (!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //保存
                try {
                    attach.transferTo(targetFile);
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("uploadFileError","* 上传失败!");
                    return "useradd";
                }
                if (i ==0){
                    idPicPath = path+File.separator+fileName;
                }else if (i==1){
                    workPicPath = path+File.separator+fileName;
                }
                logger.debug("idPicPath:"+idPicPath);
                logger.debug("workPicPath:"+workPicPath);
            }else {
                request.setAttribute("uploadFileError","* 上传图片格式不正确");
                flag = false;
                //return "useradd";
            }
        }
        if (flag){
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        user.setIdPicPath(idPicPath);
        user.setWorkPicPath(workPicPath);
        if (userService.add(user)){
            return "redirect:/user/userlist.html";
        }
        }
        return "useradd";
    }

    //第11章示例8
    @RequestMapping(value = "/add.html",method = RequestMethod.GET)
    public String add(@ModelAttribute("user")User user){
        return "userr/useradd";
    }
    @RequestMapping(value = "/add.html",method = RequestMethod.POST)
    public String addSave(@Valid User user,HttpSession session){
        user.setCreatedBy((User)session.getAttribute(Constants.USER_SESSION)).getId());
user.setCreationDate(new Date());
if (userService.add(user)){
    return "redirect:/user/userlist.html";
}
        return "user/useradd";
    }

    //第11章示例13
    @RequestMapping(value = "/usermodify.html",method = RequestMethod.GET)
    public String getUserById(@RequestParam String uid,Model model){
        logger.debug("getUserById uid=========================="+uid);
        User user = userService.getUserById(uid);
        model.addAttribute(user);
        return "usermodify";
    }

    @RequestMapping(value = "/usermodifysave.html",method = RequestMethod.POST)
    public String modifyUserSave(User user,HttpSession session){
        logger.debug("modifyUserSave userid=================="+user.getId());
        user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        if (userService.modify(user)){
            return "redirect:/user/userlist.html";
        }
        return "usermodify";
    }

    //示例16
    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public String view(@PathVariable String id,Model model){
        logger.debug("view id=================="+id);
        User user = userService.getUserById(id);
        model.addAttribute(user);
        return "userview";
    }

}
